package com.yingsheng.bi.hks.template.processor;

import com.yingsheng.bi.hks.template.events.Event;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.OrderComparator;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.List;

public class OrderedProcessors extends Processors implements InitializingBean {

    private volatile boolean ordered;

    private Comparator<Object> comparator;

    public OrderedProcessors() {
        this.comparator = OrderComparator.INSTANCE;
    }

    public Comparator<Object> getComparator() {
        return comparator;
    }

    public void setComparator(Comparator<Object> comparator) {
        this.comparator = comparator;
    }

    @Override
    public void afterPropertiesSet() {
        try {
            List<Processor> processorList = getProcessors();
            if (!CollectionUtils.isEmpty(processorList)) {
                processorList.sort(getComparator());
            }
            this.ordered = true;
        } catch (Exception e) {
            if (log.isWarnEnabled()) {
                log.warn(e.getMessage());
            }
        }
    }

    @Override
    public void exec(Event event) {
        if (!ordered) {
            synchronized (this) {
                if (!ordered) {
                    afterPropertiesSet();
                }
            }
        }
        super.exec(event);
    }

}
